package cn.ryh.netty.websocket;

import cn.ryh.netty.websocket.properties.WebsocketPropertie;
import cn.ryh.netty.websocket.server.NettyServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;

/**
 * NettySocket启动类
 *
 * @author Raoyh
 * @Description
 * @create 2023-02-23 9:58
 */
@Service
@Slf4j
public class NettySocketApplication implements ApplicationRunner {
    @Resource
    WebsocketPropertie websocketPropertie;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        try {
            if (websocketPropertie.getEnable()) {
                ExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(1,
                    new BasicThreadFactory.Builder().namingPattern("keep-alive").daemon(true).build());
                //该服务器，处于挂起状态，不会向下启动，需要线程启动，不影响业务的进行
                scheduledExecutorService.execute( new Runnable() {
                    @Override
                    public void run() {
                        try {
                            new NettyServer(websocketPropertie.getPort()).createNetty();
                        } catch (Exception e) {
                            log.error("websocket配置失败", e);
                        }
                    }
                });
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
